package com.leetcode;

import com.leetcode.Common.ListNode;

public class AddTwoNumbers_2 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode();
        ListNode p1 = dummy, p2;
        int temp = 0;
        while (l1 != null || l2 != null) {
            int val1 = l1 == null ? 0 : l1.val;
            int val2 = l2 == null ? 0 : l2.val;
            p2 = new ListNode();
            temp = temp / 10 + val1 + val2;
            p2.val = temp % 10;
            p1.next = p2;
            p1 = p1.next;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (temp >= 10) {
            p2 = new ListNode();
            p2.val = 1;
            p1.next = p2;
        }
        return dummy.next;
    }
}
